package com.example.Controller;

import com.example.Domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Reader;

@Controller
@CrossOrigin(origins = "*")
public class StudentController {

    private SqlSession sqlSessions() {
        String resource = "mybatis-config.xml";
        try (Reader reader = Resources.getResourceAsReader(resource)) {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            return sqlSessionFactory.openSession();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(value = "/loginPages", method = RequestMethod.GET)
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/signPages", method = RequestMethod.GET)
    public String signPage() {
        return "sign";
    }

    @RequestMapping(value = "/indexPage", method = RequestMethod.GET)
    public String indexPage() {
        return "index1";
    }

    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public String login(Student student, HttpServletRequest request) {
        // 硬编码的用户名和密码
        String hardcodedUsername = "test";
        String hardcodedPassword = "123456";

        // 校验用户名和密码
        if (hardcodedUsername.equals(student.getUsername()) && hardcodedPassword.equals(student.getPassword())) {
            System.out.println("登录成功: " + student);
            return "index1";
        } else {
            System.out.println("登录失败: 用户名或密码错误");
            request.setAttribute("errorMessage", "用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public String register(Student student) {
        try (SqlSession sqlSession = sqlSessions()) {
            int result = sqlSession.insert("com.example.Dao.StudentMapper.AddStudent", student);
            sqlSession.commit();
            if (result == 1) {
                System.out.println("注册成功: " + student);
                return "login";
            } else {
                System.out.println("注册失败");
                return "sign";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}